/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.googlecode.ivybeans.module.completion.ivyfiles;

import com.googlecode.ivybeans.facade.IvyLibrary;
import java.io.IOException;
import javax.swing.text.JTextComponent;
import org.apache.ivy.Ivy;
import org.netbeans.api.project.Project;
import org.netbeans.api.project.ProjectManager;
import org.netbeans.spi.editor.completion.CompletionProvider;
import org.netbeans.spi.editor.completion.CompletionTask;
import org.netbeans.spi.editor.completion.support.AsyncCompletionTask;
import org.openide.filesystems.FileObject;
import org.openide.loaders.DataObject;
import org.openide.windows.TopComponent;

/**
 * Completion provider for Ivy files, complementing schema based completion 
 * implemented by netbeans + IvyFileCompletionModelProvider.
 * <p>
 * This completion provider is responsible for what can't be deduced by schema 
 * only, like repository aware completion.
 * </p>
 * 
 * @author Xavier Hanin
 */
public class IvyFileCompletionProvider implements CompletionProvider {

    public CompletionTask createTask(int queryType, JTextComponent component) {
        if (queryType == COMPLETION_QUERY_TYPE || queryType == COMPLETION_ALL_QUERY_TYPE) {

            return new AsyncCompletionTask(new CompletionQuery(getIvyInstance()), component);
        }
        return null;
    }

    
    public int getAutoQueryTypes(JTextComponent component, String typedText) {
        return COMPLETION_QUERY_TYPE;
    }

    private Ivy getIvyInstance() {
        Project project = getProject();
        if (project == null) {
            return null;
        }
        IvyLibrary ivyLibrary = (IvyLibrary) project.getLookup().lookup(IvyLibrary.class);
        if (ivyLibrary != null) {
            return ivyLibrary.getIvyInstance();
        } else {
            return null;
        }
    }

    private Project getProject() {
        FileObject file = getPrimaryFile();
        if (file != null) {
            ProjectManager projectManager = ProjectManager.getDefault();

            while (file != null && (!file.isFolder() || !projectManager.isProject(file))) {
                file = file.getParent();
            }
            if (file != null) {
                try {
                    return projectManager.findProject(file);
                } catch (IOException ex) {
                    return null;
                } catch (IllegalArgumentException ex) {
                    return null;
                }
            }
        }
        return null;
    }

    private FileObject getPrimaryFile() {
        TopComponent activatedTC = TopComponent .getRegistry().getActivated();
        if(activatedTC == null)
            return null;
        DataObject activeFile = activatedTC.getLookup().lookup(DataObject.class);
        if(activeFile == null)
            return null;

        return activeFile.getPrimaryFile();
    }
}
